package in.hooray.panel.handler.impl;

import in.hooray.panel.handler.IFileHandler;
import in.hooray.panel.service.FileService;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;

@Component
public class QiniuFileHandler implements IFileHandler {
	
	@Autowired
	private FileService fileService;
	
	@Value("${host}")
    private String host;
    @Value("${qiniu.ak}")
    private String ak;
    @Value("${qiniu.sk}")
    private String sk;
    @Value("${qiniu.bucket}")
    private String bucket;
    @Value("${qiniu.fileHost}")
    private String qiniuHost;

	@Override
	public Map<String, Object> getToken(String appId, String name) {
		Auth auth = Auth.create(ak, sk);
        //文件名为 appId/key
        String fileName = appId + "/" + fileService.getFileKey();
        //生成上传策略
        StringMap policy = new StringMap();
        policy.put("callbackUrl", host + "file/callback");
        policy.put("callbackBody", "platform=qiniu&name=$(fname)&source=" + name + "&app=" + appId);
        String token = auth.uploadToken(bucket, fileName, 60000, policy);
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("name", fileName);
        return result;
	}

	@Override
	public Map<String, Object> callback(String body, HttpServletRequest request)
			throws Exception {
		return null;
	}

	
}
